#define _CRT_SECURE_NO_WARNINGS 1

//https://leetcode.cn/problems/cut-off-trees-for-golf-event/

class Solution {
int m, n;
public:
    int cutOffTree(vector<vector<int>>& forest) {
        m = forest.size(), n = forest[0].size();
        vector<pair<int, int>> tree;
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                if (forest[i][j] > 1) tree.push_back({ i,j });

        sort(tree.begin(), tree.end(), [&](const pair<int, int>& p1, const pair<int, int>& p2)
            {
                return forest[p1.first][p1.second] < forest[p2.first][p2.second];
            });

        int ret = 0;
        int dx = 0, dy = 0;
        for (auto& [x, y] : tree)
        {
            int step = bfs(forest, dx, dy, x, y);
            if (step == -1) return -1;
            ret += step;
            dx = x, dy = y;
        }
        return ret;
    }

    int Dx[4] = { 0,0,1,-1 };
    int Dy[4] = { 1,-1,0,0 };
    int bfs(vector<vector<int>>& forest, int dx, int dy, int endx, int endy)
    {
        if (dx == endx && dy == endy) return 0;
        queue<pair<int, int>> q;
        q.push({ dx,dy });
        bool vis[51][51] = { false };
        vis[dx][dy] = true;
        int step = 0;
        while (q.size())
        {
            step++;
            int sz = q.size();
            while (sz--)
            {
                auto [a, b] = q.front();
                q.pop();
                for (int i = 0; i < 4; i++)
                {
                    int x = a + Dx[i], y = b + Dy[i];
                    if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && forest[x][y] != 0)
                    {
                        if (x == endx && y == endy) return step;
                        q.push({ x,y });
                        vis[x][y] = true;
                    }
                }
            }
        }
        return -1;
    }
};